package com.lagou.edu.filter;

import com.lagou.edu.feign.UserServiceFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    static List<String> whiteList = new ArrayList<>();

    static {
//        whiteList.add("/api/user/");
        whiteList.add("/api/code/");
    }

    @Resource
    UserServiceFeign userServiceFeign;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        URI uri = exchange.getRequest().getURI();
        String path = uri.getPath();
        for (String s : whiteList) {
            if(path.startsWith(s)){
                // 合法请求，放行，执行后续的过滤器
                return chain.filter(exchange);
            }
        }
        HttpCookie httpCookie = exchange.getRequest().getCookies().getFirst("token");
        if(httpCookie!=null&&httpCookie.getValue()!=null&&userServiceFeign.info(httpCookie.getValue())!=null){
            // 合法请求，放行，执行后续的过滤器
            return chain.filter(exchange);
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
